import {action, observable} from "mobx-miniprogram"
import http from "../utils/request"
export const store = observable({
  activePage:0,//当前激活页面
  section:"当前板块",//当前选择板块
  sectionList:null,//板块列表
  showSection:false,//是否展示Section列表
  categoryData:null,//全部Category
  categoryList:null,//首页Category列表
  activeCategory:null,//当前选择的category
  blogList:null,//blog数据列表
  blogViewInfo:{
    page:0,
    size:10,
    total:0
  },
  toastMessage:"",
  updateActivePage:action(function(pageIndex){//更改激活页面效果
    this.activePage = pageIndex
  }),
  updateShowSection:action(function(show){//隐藏、显示科目分类页
    this.showSection = show
  }),
  getCategory:action(function(resolve,reject){//获取全部的category
    if(this.categoryData==null){
      http.get({
        url:"/category/all"
      }).then(res=>{
        this.categoryData = res.data.data
        for(let i=0;i<this.categoryData.length;i++){
          if(this.categoryData[i][0].section_id==this.section.section_id){
            this.categoryList = this.categoryData[i]
            this.activeCategory = this.categoryList[0]
            break;
          }
        }
        resolve()
      })
    }
    else{
      for(let i=0;i<this.categoryData.length;i++){
        if(this.categoryData[i][0].section_id==this.section.section_id){
          this.categoryList = this.categoryData[i]
          this.updateActiveCatory(this.categoryList[0])
          break
        }
      }
    }
  }),
  updateActiveCatory:action(function(item){//更改激活category
    this.activeCategory = item
    this.blogViewInfo = {
      page:0,
      size:10,
      total:0
    }
    this.blogList = []
    this.getBlogListByPage()
  }),
  getSectionList:action(function(resolve,reject){//获取section列表
    if(this.sectionList==null){
      http.get({
        url:"/section",
      }).then(res=>{
        if(res.data.data){
          this.sectionList = res.data.data
          this.section = this.sectionList[0]
        }
        if(resolve){
          resolve()
        }
      },
      res=>{
        reject()
      })
    }
    else{
      if(resolve){
        resolve()
      }
    }
  }),
  updateSection:action(function(item){//更改激活的section
    this.section = item
    this.getCategory()
  }),
  setToastMessage:action(function(message){
    this.toastMessage = message
  }),
  getBlogListByPage:action(function(resolve,reject){
    http.get({
      url:"/blog/getblog?category_id="+this.activeCategory.category_id+"&page="+this.blogViewInfo.page+"&size="+this.blogViewInfo.size
    }).then(res=>{
      if(this.blogList==null){
        this.blogList = []
      }
      this.blogViewInfo.total = res.data.data.total
      this.blogList = this.blogList.concat(res.data.data.data)
      if(resolve){
        resolve()
      }
    },
    res=>{
      if(reject){
        reject()
      }
    })
  }),
  addPage:action(function(resolve,reject){
    this.blogViewInfo.page++
    this.getBlogListByPage(resolve,reject)
  })
})